﻿const apiUrl = "/api/actions.aspx";

$(function () {
    $('ul.nav > li').removeClass('hover')
    $("#fun" + menuId).addClass("hover");



    /*侧栏导航*/
    $(".side ul li").hover(function () {
        $(this).find(".sidebox").stop().animate({ "width": "160px" }, 100).css({ "opacity": "1", "filter": "Alpha(opacity=100)", "background": "#2aac22" })
    }, function () {
        $(this).find(".sidebox").stop().animate({ "width": "54px" }, 100).css({ "opacity": "1", "filter": "Alpha(opacity=100)", "background": "#2aac22" })
    });

    /*友情链接*/
    $(".friend_link").hover(function () {
        $(this).parent().find("ul").show();
    }, function () {
        $(this).parent().find("ul").hide();
    })
    $('#shareContainer').share();
})

const getUrl = function (action, para) {
    var url = apiUrl + "?action=" + action;
    if (para) url = url + "&" + para;
    return url;
}
const getUrlPara = function (paraName) {
    var reg = new RegExp("(^|&)" + paraName + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}
const getdata = function (action, data, callback) {
    var url = apiUrl + "?action=" + action;
    $.getJSON(url, data, function (ret, status) {
        callback(ret, status)
    });
}
var sliderMain = function () {
    $('.flexslider').flexslider({
        animation: "fade",
        slideshowSpeed: 5000, //展示时间间隔ms
        animationSpeed: 1000, //滚动时间ms
        touch: true, //是否支持触屏滑动
        directionNav: true,
        prevText: '<',
        nextText: '>',
        controlNav: true
    });
}
function goTop() {
    $('html,body').animate({ 'scrollTop': 0 }, 500);
}
String.prototype.byteLength = function () {
    if (this == null) return 0;
    return this.replace(/[^\x00-\xff]/g, "01").length;
}
String.prototype.len = function () {
    if (this == null) return 0;
    return this.replace(/[^\x00-\xff]/g, "01").length;
}
$(function() {
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?2cda2382298076ebbc1b7bc98c25a5af";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
})
//Set maxlength for multiline TextBox
function setMaxLength(object, length) {
    var result = true;
    //var controlid = document.selection.createRange().parentElement().id;
    var controlValue = object.value;
    if (object.value != "" && object.value.byteLength() < length) {
        result = true;
    }
    else if (object.value.byteLength() > length) {
        result = false;
    }
    window.event.returnValue = result;
    return result;
    //if (window.event) {
    //    window.event.returnValue = result;
    //    return result;
    //}
}
//Check maxlength for multiline TextBox when paste
function limitPaste(object, length) {
    //var tempLength = 0;
    //if (document.selection) {
    //    if (document.selection.createRange().parentElement().id == object.id) {
    //        tempLength = document.selection.createRange().text.len();
    //    }
    //}
    var tempValue = window.clipboardData.getData("Text");
    tempLength = object.value.len() + tempValue.len() - tempLength;
    if (tempLength > length) {
        tempLength -= length;
        var tt = "";
        for (var i = 0; i < tempValue.len() - tempLength; i++) {
            if (tt.len() < (tempValue.len() - tempLength))
                tt = tempValue.substr(0, i + 1);
            else
                break;
        }
        tempValue = tt;
        window.clipboardData.setData("Text", tempValue);
    }
    //window.event.returnValue = true;
}
$(function () {
    document.addEventListener('paste', function (e) {
        pasteEvent(e);
    });
});
const max_text_byte_len = 511;

function pasteEvent(e) {
    //if (e.target.id != 'jcContent') return false;
    if (!$('#rdBD')[0].checked) return false;
    var clipboardData = e.clipboardData;
    if (!(clipboardData && clipboardData.items)) { return false; }//是否有粘贴内容
    var pasteText = e.clipboardData.getData("Text"); 
    if (!pasteText) return false;
    //if (e.target.value.len() >= 511) { window.event.returnValue = false; return false;}

    var beforePastedValue = e.target.value;
    var before_CurStart = e.target.selectionStart;
    var before_CurEnd = e.target.selectionEnd;
    var result = true;
    var strLen = beforePastedValue.substr(0, before_CurStart).len() + pasteText.len() + beforePastedValue.substr(before_CurEnd);
    if (strLen >= 511) result = false;
    window.event.returnValue = result;
    if (!result) { layer.alert("文本长度过长！", {icon:6})}
    return result;

    //var newText = '';
    //if (before_CurStart == before_CurEnd) {//没有选中textarea中的内容时
    //    if (beforePastedValue.len() + pasteText.len() <= max_text_byte_len) {
    //        //newText = beforePastedValue.substr(0, before_CurStart) + pasteText + beforePastedValue(before_CurStart);
    //        //e.target.value = newText;
    //        return;
    //    }
    //    else {
    //        var len = pasteText.len() - (beforePastedValue.len() + pasteText.len() - 511);
    //        newText = beforePastedValue.substr(0, before_CurStart) + pasteText.substr(0, len) + beforePastedValue.substr(before_CurStart);
    //        e.target.value = newText;
    //    }
    //}
    //else if (before_CurEnd > before_CurStart) {//选中textarea中的内容时

    //}
    //for (var i = 0, len = clipboardData.items.length; i < len; i++) {
    //    var item = clipboardData.items[i];
    //    if (item.kind === "string" && item.type == "text/plain") {
    //        item.getAsString(function (str) {
    //            var afterPasteValue = e.target.value;
    //            var after_CurStart = e.target.selectionStart;
    //            var after_CurEnd = e.target.selectionEnd;

    //            var tempLength = 0;
    //            if (e.target.selectionEnd - e.target.selectStart > 0) {  //有选中内容
    //                tempLength = e.taget.selectionEnd - e.taget.selectionStart;
    //            }
    //            else if (e.target.selectionEnd - e.target.selectionStart == 0) {

    //            }

    //            var tempValue = clipboardData.getData("Text");
    //            tempLength = e.target.value.len() + tempValue.len() - tempLength;
    //            if (tempLength > length) {
    //                tempLength -= length;
    //                var tt = "";
    //                for (var i = 0; i < tempValue.len() - tempLength; i++) {
    //                    if (tt.len() < (tempValue.len() - tempLength))
    //                        tt = tempValue.substr(0, i + 1);
    //                    else
    //                        break;
    //                }
    //                tempValue = tt;
                    
    //                //window.clipboardData.setData("Text", tempValue);
    //            }
    //            //window.event.returnValue = true;
    //            // str 是获取到的字符串,创建文本框
    //            //处理粘贴的文字内容
    //        })
    //    }
    //    //else if (item.kind === "file") {//file 一般是各种截图base64数据
    //    //    var pasteFile = item.getAsFile();
    //    //    // pasteFile就是获取到的文件
    //    //    var reader = new FileReader();
    //    //    reader.onload = function (event) {
    //    //        var base64Img = event.target.result;
    //    //    }; // data url
    //    //    reader.readAsDataURL(pasteFile);
    //    //}
    //    //var copy_content = e.clipboardData.getData('text/plain');
    //}
}
function getCursorPosition(obj) {
    var evt = window.event ? window.event : getTa1CursorPosition.caller.arguments[0];
    var oTa1 = document.getElementById(obj);
    try {
        if (oTa1.value == "") return 0;
        var cursurPosition = -1;
        if (oTa1.selectionStart) {//非IE浏览器
            cursurPosition = oTa1.selectionStart;
        } else {//IE
            var rngSel = document.selection.createRange();//建立选择域
            var rngTxt = oTa1.createTextRange();//建立文本域
            var flag = rngSel.getBookmark();//用选择域建立书签
            rngTxt.collapse();//瓦解文本域到开始位,以便使标志位移动
            rngTxt.moveToBookmark(flag);//使文本域移动到书签位
            rngTxt.moveStart('character', -oTa1.value.length);//获得文本域左侧文本
            cursurPosition = rngTxt.text.replace(/\r\n/g, '').length;//替换回车换行符
        }
        return cursurPosition;
    }
    catch (e) {
        return oTa1.value.length;
    }

}

function textCorrect() {
    var index = layer.load(1, { shade: [0.1, '#fde5e5'] });//0.1透明度的白色背景
    $.ajax({
        type: 'POST',
        url: getUrl("text_correct"),
        data: $("#formContent").serialize(),
        dataType: 'json',
        success: function (ret, stutas, xhr) {
            layer.close(index);
            if (ret.error_code && ret.error_code != 0) { layer.alert(ret.error_msg, { icon: 6 }); return false; }
            _text = hightlight_replaced_words(ret);
            $('#afterJC').html(_text);
            var html = "<span>全文共 " + ret.text.length + " 字（" + ret.text.len() + "个字节）</span>";
            html = html + "<span style='margin-left:15px;'>共有 " + ret.item.vec_fragment.length + " 个词(字)被纠正</span>";
            html = html + "<span style='margin-left:15px;'>置信度 " + ret.item.score + " </span>";
            $('#jcStatic').html(html);
            html = '';
            $.each(ret.item.vec_fragment, function (index, item) {
                var rowId = index + 1;
                if (rowId % 2 == 0) {
                    html += "<div class='bannedword-col keyword-col' style='background:#d2f383;'>" + rowId + "-" + item.ori_frag + "</div>";
                    html += "<div class='bannedword-col type-col' style='background:#d2f383;'>" + item.correct_frag + "</div>";
                    html += "<div class='bannedword-col count-col' style='background:#d2f383;'></div>";
                }
                else {
                    html += "<div class='bannedword-col keyword-col'>" + rowId + "-" + item.ori_frag + "</div>";
                    html += "<div class='bannedword-col type-col'>" + item.correct_frag + "</div>";
                    html += "<div class='bannedword-col count-col'></div>";
                }
            });
            $('#jcDetail').html(html);
        },
        error: function (xhr, textStatus, data) {
            layer.close(index);
            layer.alert(data, { icon: 6 });
        }
    })
}

const hightlight_replaced_words = function (data) {
    var text = data.item.correct_query;
    for (let i in data.item.vec_fragment) {
        let res = article_add_color(data.item.vec_fragment[i].correct_frag, '#ff0000', text);
        if (res !== false) {
            text = res;
        }
    }
    return text;
}
const hightlight_original_words = function (data) {
    var text = data.text;
    for (let i in data.item.vec_fragment) {
        let res = article_add_color(data.item.vec_fragment[i].ori_frag, '#00ff00', text);
        if (res !== false) {
            text = res;
        }
    }
    return text;
}
const article_add_color = function (words_name, color, article) {
    let str = (article.split(words_name)).length - 1; //article.indexOf(words_name);
    if (str !== -1) {
        let words_name1 = words_name.replace(new RegExp("\\?", 'g'), "\\\?");
        words_name1 = words_name1.replace(new RegExp("\\+", 'g'), "\\\+");
        const reg = new RegExp(words_name1, 'g');
        article = article.replace(reg, '<font style="background-color:' + color + ';color:white;">' + words_name + '</font>');
        return article;
    } else {
        return false
    }
}